<template>
  <view>
    <view style="margin-top: 10rpx">
      <scroll-view
        :lower-threshold="42"
        @scrolltolower="scrollLoading"
        scroll-y
        class="list-ul"
      >
        <view
          v-for="(item, index) in unitList"
          :key="index"
          class="list-item clearfix"
          @click="checkFinance(item)"
        >
          <view
            class="float_left sel-view"
            @click.stop="toggleCheck(item)"
            v-if="source === 2"
          >
            <text v-if="!item.checked">○</text>
            <text v-else>●</text>
          </view>
          <view :class="[source === 2 ? 'float_left' : '']">
            <view class="list-label clearfix">
              <view class="float_left list-name">{{ item.unitName }}</view>
              <view class="float_right status-text">
                <text
                  :style="{
                    fontSize: '24rpx',
                    color: item.enableStatus === 5 ? '#67C23A' : '#F56C6C',
                    border: '1rpx solid',
                    borderColor:
                      item.enableStatus === 5 ? '#67C23A' : '#F56C6C',
                    borderRadius: '8rpx',
                    padding: '2rpx 10rpx',
                  }"
                >
                  {{ item.enableStatus === 5 ? "启用" : "禁用" }}
                </text>
              </view>
              <view class="float_right status-text" v-if="hasEditOrDel">
                <button
                  size="mini"
                  v-if="hasEdit"
                  @click.stop="Edit({ text: '编辑' }, item)"
                >
                  编辑
                </button>
                <button
                  size="mini"
                  type="warn"
                  v-if="hasDel"
                  @click.stop="Edit({ text: '删除' }, item)"
                >
                  删除
                </button>
                <button
                  size="mini"
                  :class="
                    item.enableStatus === 4 ? 'btn-enable' : 'btn-disable'
                  "
                  @click.stop="statusSet(item)"
                  style="margin-left: 8rpx"
                >
                  {{ item.enableStatus === 4 ? "启用" : "禁用" }}
                </button>
              </view>
            </view>
          </view>
        </view>
        <view
          v-if="loading_status === 'loading'"
          style="text-align: center; padding: 20rpx; color: #999"
          >加载中...</view
        >
        <view
          v-if="loading_status === 'noMore' && unitList.length"
          style="text-align: center; padding: 20rpx; color: #999"
          >没有更多了</view
        >
        <view style="height: 120rpx" v-if="source === 2"></view>
      </scroll-view>
    </view>
    <view class="fixed-bottom" v-if="source === 2">
      <view class="sub-btn" @click="selConfirm">确定</view>
    </view>
    <view style="position: fixed; right: 40rpx; bottom: 120rpx; z-index: 10">
      <button type="primary" @click="goAddUnit">新增</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      unitList: [],
      pageSize: 20,
      page: 1,
      pageTotal: 0,
      loading_status: "noMore",
      source: 0,
      loadingMore: false,
      needRefresh: false, // 新增：用于页面返回时判断是否刷新
    };
  },
  computed: {
    hasEdit() {
      return this.$accessCheck && this.$accessCheck(this.$Access.UnitSetAdd);
    },
    hasDel() {
      return this.$accessCheck && this.$accessCheck(this.$Access.UnitSetDel);
    },
    hasEditOrDel() {
      return this.hasEdit || this.hasDel;
    },
  },
  onLoad(options) {
    this.source = parseInt(options.source) || 0;
    this.page = 1;
    this.getAllUnit();
    // 监听刷新事件，设置刷新标志
    uni.$on("unit-refresh", this.refreshList);
  },
  onShow() {
    // 页面返回时刷新
    if (this.needRefresh) {
      this.page = 1;
      this.getAllUnit();
      this.needRefresh = false;
    }
  },
  onUnload() {
    uni.$off("unit-refresh", this.refreshList);
  },
  onNavigationBarButtonTap() {
    if (!this.hasEdit) {
      this.$u.toast("没有权限");
      return;
    }
    this.goPage("/pagesB/goods/AddUnit");
  },
  onPullDownRefresh() {
    this.page = 1;
    this.getAllUnit();
  },
  onReachBottom() {
    // 页面滑动到底部时自动加载新数据
    console.log("reachBottom");
    this.scrollLoading();
  },
  methods: {
    toggleCheck(item) {
      item.checked = !item.checked;
    },
    scrollLoading() {
      // 修正：防止多次触发，且保证 loadingMore 标志正确
      if (this.loadingMore) return;
      if (this.page < Math.ceil(this.pageTotal / this.pageSize)) {
        this.page += 1;
        this.getAllUnit(true);
      }
    },
    async getAllUnit(append = false) {
      if (this.loadingMore) return; // 防止并发
      this.loading_status = "loading";
      this.loadingMore = true;
      const { err, data, pageTotal } = await this.$u.api.unitList({
        page: this.page,
        pageSize: this.pageSize,
      });
      this.loading_status = "noMore";
      this.loadingMore = false;
      uni.stopPullDownRefresh();
      // if (err) return;
      const cData = (data && data.list) || data || [];
      if (this.page === 1 || !append) {
        this.unitList = cData;
      } else {
        this.unitList = this.unitList.concat(cData);
      }
      this.pageTotal = (data && (pageTotal || total || 0)) || 0;
      if (this.page >= Math.ceil(this.pageTotal / this.pageSize)) {
        this.loading_status = "noMore";
      } else {
        this.loading_status = "loading";
      }
    },
    statusSet(item) {
      if (!this.$accessCheck(this.$Access.UnitSetUpdateEnablesStatus)) {
        this.$u.toast("没有权限");
        return;
      }
      // 取反 enableStatus，4=禁用，5=启用
      const nextStatus = item.enableStatus === 5 ? 4 : 5;
      const name = nextStatus === 5 ? "启用" : "禁用";
      uni.showModal({
        title: "提示",
        content: `确定要${name}计量单位吗?`,
        success: async (res) => {
          if (res.confirm) {
            uni.showLoading();
            const { err } = await this.$u.api.unitEnable({
              id: item.id,
              enableStatus: nextStatus,
            });
            uni.hideLoading();
            if (err) return;
            this.$u.toast(`${name}成功`);
            this.page = 1;
            this.getAllUnit();
          }
        },
      });
    },
    Edit(e, item) {
      const text = e.text;
      if (text === "删除") {
        uni.showModal({
          title: "提示",
          content: "确定要删除该计量单位吗？",
          success: async (res) => {
            if (res.confirm) {
              uni.showLoading();
              const { err } = await this.$u.api.unitDelete({ id: item.id });
              uni.hideLoading();
              if (err) return;
              this.page = 1;
              this.getAllUnit();
            }
          },
        });
      } else {
        this.goPage(
          `/pagesB/goods/AddUnit?id=${item.id}&unitName=${item.unitName}&enableStatus=${item.enableStatus}`
        );
      }
    },
    goPage(url, type = "navigateTo") {
      if (type === "redirectTo") {
        uni.redirectTo({ url });
      } else {
        uni.navigateTo({ url });
      }
    },
    checkFinance(item) {
      // 可扩展：点击列表项时的业务逻辑
    },
    selConfirm() {
      // 多选/单选模式下，返回选中的单位
      const checkedList = this.unitList.filter((u) => u.checked);
      uni.$emit("unit-selected", checkedList);
      uni.navigateBack();
    },
    refreshList() {
      // 设置刷新标志，onShow 时刷新
      this.needRefresh = true;
    },
    goAddUnit() {
      // 跳转到新增页面
      this.goPage("/pagesB/goods/AddUnit");
    },
  },
};
</script>

<style lang="scss" scoped>
.search-input {
  width: 80%;
  height: 64rpx;
  border-radius: 32rpx;
  border: 1rpx solid #e5e5e5;
  background: #f7f8fa;
  padding: 0 32rpx;
  font-size: 28rpx;
  margin-right: 16rpx;
  margin-bottom: 12rpx;
}
.clear-btn {
  display: inline-block;
  background: #f5f7fa;
  color: #999;
  border: 1rpx solid #e5e5e5;
  border-radius: 8rpx;
  font-size: 24rpx;
  padding: 8rpx 20rpx;
  margin-left: 8rpx;
}
.list-ul {
  background: #fff;
  border-radius: 16rpx;
  margin: 24rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.03);
  min-height: 300rpx;
  padding-bottom: 24rpx;
}
.list-item {
  display: flex;
  align-items: center;
  padding: 32rpx 24rpx;
  border-bottom: 1rpx solid #f0f0f0;
  transition: background 0.2s;
  &:last-child {
    border-bottom: none;
  }
  &:active {
    background: #f5f7fa;
  }
}
.list-label {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.list-name {
  font-size: 30rpx;
  color: #333;
  font-weight: 500;
  max-width: 300rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.status-text {
  margin-left: 16rpx;
}
.sel-view {
  margin-right: 20rpx;
  color: #999;
  font-size: 32rpx;
  min-width: 40rpx;
  text-align: center;
}
.fixed-bottom {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  padding: 24rpx 32rpx 32rpx 32rpx;
  box-shadow: 0 -2rpx 12rpx #eee;
  z-index: 99;
}
.sub-btn {
  background: linear-gradient(90deg, #fb5904 0%, #ff9000 100%);
  color: #fff;
  text-align: center;
  border-radius: 12rpx;
  padding: 24rpx 0;
  font-size: 32rpx;
  font-weight: 600;
  box-shadow: 0 4rpx 16rpx rgba(251, 89, 4, 0.08);
  letter-spacing: 2rpx;
}
button[type="primary"] {
  background: linear-gradient(90deg, #fb5904 0%, #ff9000 100%);
  color: #fff;
  border-radius: 50%;
  width: 96rpx;
  height: 96rpx;
  box-shadow: 0 8rpx 24rpx rgba(251, 89, 4, 0.18);
  font-size: 40rpx;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
}
button[type="primary"]:active {
  opacity: 0.8;
}
button[size="mini"] {
  min-width: 80rpx;
  height: 48rpx;
  font-size: 24rpx;
  margin-left: 8rpx;
  border-radius: 8rpx;
  background: #f5f7fa;
  color: #666;
  border: 1rpx solid #e5e5e5;
  padding: 0 20rpx;
}
button[type="warn"] {
  background: #f56c6c;
  color: #fff;
  border: none;
}
button[size="mini"]:active {
  opacity: 0.7;
}
/* 状态标签样式 */
.status-text text {
  display: inline-block;
  min-width: 60rpx;
  text-align: center;
  font-size: 24rpx;
  border-radius: 8rpx;
  padding: 2rpx 16rpx;
  font-weight: 500;
  border-width: 1rpx;
  border-style: solid;
}
/* 兼容老样式 */
.address-view {
  font-size: 24rpx;
  color: #666;
  padding-top: 10rpx;
  .ibonlocation {
    font-size: 26rpx;
    margin-right: 10rpx;
  }
}
.list-cont {
  .ibonkehu {
    font-size: 26rpx;
    margin-right: 10rpx;
  }
}
button.btn-enable {
  background: #67c23a;
  color: #fff;
  border: 1rpx solid #67c23a;
}
button.btn-disable {
  background: #f56c6c;
  color: #fff;
  border: 1rpx solid #f56c6c;
}
</style>
